import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

/**
 * Created by 4 on 2016/6/17.
 */
public class ZipUtils {

    public static void main(String[] args) {
        File file1 = new File("/电子合同(被篡改).pdf");
        File file2 = new File("D:/电子合同(多签名).pdf");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String zipFileName = "D:/" + format.format(new Date());
        String[] files = new String[]{file1.getAbsolutePath()};
        /*try {
            zip(zipFileName, "D:/", files);
            //zip("", "D:/", file1.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        if (1 == 1) {
            //String name = args[1];
            ZipUtils zip = new ZipUtils();

            //if(args[0].equals("-zip"))
            zip.doZip(file1.getPath());
            //else if(args[0].equals("-unzip"))
            // zip.unZip(name);
        } else {
            System.out.println("Usage:");
            System.out.println("压缩:java AntZip -zip directoryName");
            System.out.println("解压:java AntZip -unzip fileName.zip");
            //throw new Exception("Arguments error!");
        }

    }

    public static void zip(String zipFileName, String relativePath,
                           String directory) throws FileNotFoundException, IOException {
        String fileName = zipFileName;
        if (StringUtils.isBlank(fileName)) {
            File temp = new File(directory);
            if (temp.isDirectory()) {
                fileName = directory.concat(".zip");

            } else {
                if (directory.indexOf(".") > 0) {
                    fileName = directory.substring(0, directory.lastIndexOf(".")).concat(".zip");

                } else {
                    fileName = directory.concat(".zip");
                }
            }
        }
        //创建压缩文件输出流
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName));
        try {
            zip(zos, relativePath, directory);
        } finally {
            if (null != zos) {
                zos.close();
            }
        }
    }

    public static void zip(String zipFileName, String relativePath,
                           String[] files) throws IOException {
        String fileName = zipFileName.concat(".zip");
        //创建压缩文件输出流
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName));
        try {
            File file;
            for (String path : files) {
                file = new File(path);
                zipFile(zos, file, relativePath);
            }
        } finally {
            if (null != zos) {
                zos.close();
            }
        }
    }


    private static void zip(ZipOutputStream zos, String relativePath, String directory)
            throws IOException {
        File file = new File(directory);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File temp : files) {
                if (temp.isDirectory()) {
                    String newRelativePath = relativePath.concat(temp.getName()).concat(File.separator);
                    createZipNode(zos, newRelativePath);
                    zip(zos, newRelativePath, temp.getPath());
                } else {
                    zipFile(zos, temp, relativePath);
                }

            }
        } else {
            zipFile(zos, file, relativePath);
        }
    }

    private static void zipFile(ZipOutputStream zos, File file, String relativePath)
            throws IOException {
        ZipEntry entry = new ZipEntry(relativePath.concat(file.getName()));
        zos.putNextEntry(entry);
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            int BUFFERSIZE = 2 << 10;
            int length = 0;
            byte[] buffer = new byte[BUFFERSIZE];
            while ((length = is.read(buffer, 0, BUFFERSIZE)) >= 0) {
                zos.write(buffer, 0, length);
            }
            zos.finish();
            zos.closeEntry();
        } finally {
            if (null != is) {
                is.close();
            }
        }
    }

    private static void createZipNode(ZipOutputStream zos, String relativePath)
            throws IOException {
        ZipEntry zipEntry = new ZipEntry(relativePath);
        zos.putNextEntry(zipEntry);
        zos.close();
    }


    private ZipFile zipFile;
    private ZipOutputStream zipOut;     //压缩Zip
    private ZipEntry zipEntry;
    private static int bufSize;    //size of bytes
    private byte[] buf;
    private int readedBytes;

    public ZipUtils() {
        this(512);
    }

    public ZipUtils(int bufSize) {
        this.bufSize = bufSize;
        this.buf = new byte[this.bufSize];
    }

    //压缩文件夹内的文件
    public void doZip(String zipDirectory) {//zipDirectoryPath:需要压缩的文件夹名
        File file;
        File zipDir;

        zipDir = new File(zipDirectory);
        String zipFileName = zipDir.getAbsolutePath() + ".zip";//压缩后生成的zip文件名

        try {
            this.zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
            handleDir(zipDir, this.zipOut);
            this.zipOut.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    //由doZip调用,递归完成目录文件读取
    private void handleDir(File dir, ZipOutputStream zipOut) throws IOException {
        FileInputStream fileIn;
        File[] files;

        if (dir.isDirectory()) {
            files = dir.listFiles();

            if (files.length == 0) {//如果目录为空,则单独创建之.
                //ZipEntry的isDirectory()方法中,目录以"/"结尾.
                this.zipOut.putNextEntry(new ZipEntry(dir.toString() + "/"));
                this.zipOut.closeEntry();
            } else {//如果目录不为空,则分别处理目录和文件.
                for (File fileName : files) {
                    //System.out.println(fileName);

                    if (fileName.isDirectory()) {
                        handleDir(fileName, this.zipOut);
                    } else {
                        fileIn = new FileInputStream(fileName);
                        this.zipOut.putNextEntry(new ZipEntry(fileName.toString()));

                        while ((this.readedBytes = fileIn.read(this.buf)) > 0) {
                            this.zipOut.write(this.buf, 0, this.readedBytes);
                        }

                        this.zipOut.closeEntry();
                    }
                }
            }
        }else{
            fileIn = new FileInputStream(dir);
            this.zipOut.putNextEntry(new ZipEntry(dir.toString()));

            while ((this.readedBytes = fileIn.read(this.buf)) > 0) {
                this.zipOut.write(this.buf, 0, this.readedBytes);
            }

            this.zipOut.closeEntry();
        }


    }

    //解压指定zip文件
    public void unZip(String unZipfileName) {//unZipfileName需要解压的zip文件名
        FileOutputStream fileOut;
        File file;
        InputStream inputStream;

        try {
            this.zipFile = new ZipFile(unZipfileName);

            for (Enumeration entries = this.zipFile.getEntries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                file = new File(entry.getName());

                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    //如果指定文件的目录不存在,则创建之.
                    File parent = file.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }

                    inputStream = zipFile.getInputStream(entry);

                    fileOut = new FileOutputStream(file);
                    while ((this.readedBytes = inputStream.read(this.buf)) > 0) {
                        fileOut.write(this.buf, 0, this.readedBytes);
                    }
                    fileOut.close();

                    inputStream.close();
                }
            }
            this.zipFile.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    //设置缓冲区大小
    public void setBufSize(int bufSize) {
        this.bufSize = bufSize;
    }

}
